package org.wattdepot.cli;

import org.wattdepot.cli.processor.CommandProcessor;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.client.WattDepotClientException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * A simple command line interface to WattDepot that shows basic connection and processing.
 * 
 * @author Philip Johnson, George Lee, Yichi Xu
 */
public class CommandLineInterface {
  /** The URL to the public WattDepot Server. */
  /** Processes the commands for the command line interface.*/
  private CommandProcessor processor;

  /**
   * Connect to the service and execute some simple commands. Returns immediately if a connection to
   * the service could not be obtained.
   * @param url The URL to the WattDepot server. 
   */
  public CommandLineInterface(String url) {
    WattDepotClient client = new WattDepotClient(url);
    // Stop right away if we cannot contact server.
    if (!client.isHealthy()) {
      System.out.println("Failed to connect to " + client.getWattDepotUri());
      return;
    }
    this.processor = new CommandProcessor(client);
    
    // Indicate successful connection.
    System.out.println("Connected to " + client.getWattDepotUri());
  }

  /**
   * Starts the command loop for the command line interface.
   */
  private void startCommandLoop() {
    String command;
    String result;

    while (true) {
      // prompt the user to enter their command
      System.out.print(">");

      // open up standard input
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      try {
        command = br.readLine();
        result = this.processor.processCommand(command);
        System.out.println(result);
      }
      catch (IOException ioe) {
        System.out.println("IO error trying to read your command. Exiting");
        throw new RuntimeException(ioe);
      }
    }
  }

  /**
   * The main program that is invoked from 'java -jar wattdepot-cli.jar'.
   * 
   * @param args If an arg is present, it is interpreted as the WattDepot URL.
   * If missing, connects to the default WattDepot URL.
   * @throws WattDepotClientException If anything goes wrong.
   */
  public static void main(String[] args) throws WattDepotClientException {
    String url = (args.length > 0) ? args[0] : "http://server.wattdepot.org:8182/wattdepot/";
    System.out.println("Connecting to WattDepot server at: " + url);
    CommandLineInterface cli = new CommandLineInterface(url);
    System.out.println("Starting command interface.");
    try {
      cli.startCommandLoop();
    }
    catch (RuntimeException e) {
      System.out.println("Exiting Wattdepot CLI");
      System.exit(0);
    }
  }
}